angular.module('controllers',['ngPlugin'])
    .controller('formController',['$scope','$timeout','tinymceConfig','notify','$http','$state','$stateParams',function($scope,$timeout,tinymceConfig,notify,$http,$state,$stateParams){
        $scope.tabIndex = $stateParams.tabIndex?$stateParams.tabIndex:1;
        function GetRequest() {
            var url = location.search; //获取url中"?"符后的字串
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=decodeURIComponent(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
        $scope.params = GetRequest();
        $scope.activity_id = $scope.params.activity_id||($stateParams.activity_id!='0'?$stateParams.activity_id:'');
        $scope.isEdit = Boolean($scope.params.activity_id);
        $scope.controls = [{
            value: 'IP',
            name: '同IP限答一次',
        },{
            value: 'MOBILE',
            name: '验证电话号码',
        },{
            value: 'VERIFY_CODE',
            name: '验证码验证',
        },{
            value: 'PASSWORD',
            name: '密码验证',
            password: '',
        }];
        $scope.postData = {
            name: '',
            category: $scope.params.category,
            start_time: '',
            end_time: '',
            background_img: '',
            model_id: $scope.params.model_id,
            template_id: $scope.params.template_id,
            description: '',
            list_background_img: '',
            // app_url: '',
            validations: [],
            shares: {
                isopen: 'off',
                title: '',
                content: ''
            }
        }
        // 授权和平台设置================================================
        $scope.channel = {
            app: {
                is_open: 'off',
                app_urls: []
            },
            wechat: {
                is_open: 'off',
                qr_code: []
            }
        }
        $scope.isAuthorize = -1;//是否授权
        $scope.authorize = {};//授权信息
        function requestAuthorize() {
            $http({
                method: 'get',
                url: '/web-api/configurations/wechat',
                headers: JSON.parse($('meta[name="profile"]').attr('content')),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
            }).success(function (data) {
                if (data.code == 200) {
                    if (data.data['app_id'] && data.data['app_secret'] && data.data['group_code']) {
                        $scope.isAuthorize = 1;
                        $scope.authorize = data.data;
                    } else {
                        $scope.isAuthorize = 0;
                    }
                } else {
                    notify(data.message, 3);
                    $scope.isAuthorize = 0;
                }
            }).error(function (data) {
                notify(data.message, 3);
            });
        }
        requestAuthorize();
        function requestChannel() {
            $http({
                method: 'get',
                url: '/web-api/publishing/' + $scope.activity_id,
                headers: JSON.parse($('meta[name="profile"]').attr('content')),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
            }).success(function (data) {
                if (data.code == 200) {
                    $scope.channel = {
                        app: {
                            is_open: data.data.app['is_open']?data.data.app['is_open']:'off',
                            app_urls: data.data.app['app_urls']?data.data.app['app_urls']:[]
                        },
                        wechat: {
                            is_open: data.data.wechat['is_open']?data.data.wechat['is_open']:'off',
                            qr_code: data.data.wechat['qr_code']?data.data.wechat['qr_code']:[]
                        }
                    }
                    $scope.refresh  = true;
                } else {
                    notify(data.message, 3);
                }
            }).error(function (data) {
                notify(data.message, 3);
            });
        }
        if($scope.activity_id){
            requestChannel();
        }
        function createChannel(callback) {
            $http({
                method: 'POST',
                url: '/web-api/publishing/' + $scope.activity_id,
                headers: JSON.parse($('meta[name="profile"]').attr('content')),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: $scope.channel
            }).success(function (data) {
                if (data.code == 200) {
                    callback();
                    // notify(data.message, 2);
                } else {
                    notify(data.message, 3);
                }
            }).error(function (data) {
                notify(data.message, 3);
            });
        }
        $scope.toggleClass = function($event,type){
            if($scope.isAuthorize!=1) {
                bootbox.confirm({
                    title: '提示:',
                    message: "您还未授权公众号，是否现在授权？",
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-danger'
                        }
                    },
                    callback: function (result) {
                        if(result){
                            ngModal({
                                templateUrl: '/components/addSubscription.html',
                                controller: 'subscriptionModalController',
                                resolve: {
                                    items: function () {
                                        return {
                                            isAuthorize: $scope.isAuthorize,
                                            authorize: $scope.authorize
                                        };
                                    }
                                },
                                ok: function (authorize) {
                                    $scope.channel.wechat.is_open = 'on';
                                },
                                cancel: function () {

                                }
                            });
                        }
                    }
                });
            }else{
                if(type=='label'){
                    if($scope.channel.wechat.is_open=='on'){
                        $scope.channel.wechat.is_open = 'off';
                    }else{
                        $scope.channel.wechat.is_open = 'on';
                    }
                }else{
                    $scope.channel.wechat.is_open = type;
                }
            }
        }
        // 提交数据验证================================================
        function validateData(){
            var validate = {
                msg: '',
                flag: false
            },keep=true,count=0;
            if(!$scope.postData.name){
                validate.msg = '请输入活动名称';
            }else if($scope.postData.name&&$scope.postData.name.length>20){
                validate.msg = '活动名称最多不超过20个字符';
            }else if(!$scope.postData.start_time){
                validate.msg = '开始时间不能为空';
            }else if(!$scope.postData.end_time){
                validate.msg = '结束时间不能为空';
            }else if($scope.postData.start_time>$scope.postData.end_time){
                validate.msg = '结束时间不能小于开始时间';
            }else if(!$scope.postData.description){
                validate.msg = '活动简介不能为空';
            }else if($scope.channel.app.is_open=='on'&&$scope.channel.app.app_urls[0]&&!/^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test($scope.channel.app.app_urls[0])) {
                validate.msg = '请输入正确的链接（例如：http://www.chinamcloud.com）';
            }else if($scope.postData.shares.isopen=='on'){
                if(!$scope.postData.shares.title){
                    validate.msg = '分享标题不能为空';
                }else if(!$scope.postData.shares.content){
                    validate.msg = '分享内容不能为空';
                }else if(!$scope.postData.shares.thumb){
                    validate.msg = '分享图片不能为空';
                }else{
                    validate.flag = true;
                }
            }else{
                validate.flag = true;
            }
            return validate;
        }
        // ================================================
        if($scope.activity_id){
            $http({
                method: 'GET',
                url: '/web-api/activities/'+$scope.activity_id,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
            }).then(function(httpData){
                var data = httpData.data;
                if(data.code==200){
                    $scope.postData = {
                        name: data.data.name,
                        category: data.data.category,
                        start_time: data.data.start_time,
                        end_time: data.data.end_time,
                        background_img: data.data.background_img,
                        list_background_img: data.data.list_background_img,
                        app_url: data.data.app_url,
                        model_id: data.data.model_id,
                        template_id: data.data.template_id,
                        description:  data.data.description,
                        validations: data.data.rule.validations,
                        shares: $.isEmptyObject(data.data.shares)?{
                            isopen: 'off',
                            title: '',
                            content: ''
                        }:data.data.shares,
                    };
                    angular.forEach($scope.controls,function(item,i){
                        angular.forEach(data.data.rule.validations,function(v,index){
                            if(v.type==item.value){
                                item.checked = true;
                                if(v.type=='PASSWORD'){
                                    item.password = v.password;
                                }
                            }
                        });
                    });
                    $scope.refresh = true;
                }else{
                    notify(data.message,3);
                }
            },function(httpData){
                var data = httpData.data;
                notify(data.message,3);
            });
        }
        //图片上传配置
        $scope.fileConfig = {
            config: {
                language: 'zh',
                maxFileCount: 1,
                maxFileSize: 200,
            },
        }
        //富文本配置
        $scope.tinymceOptions = angular.extend({},tinymceConfig,{
            setup : function(ed) {
                ed.on('blur', function(e) {
                    // console.log(tinymce.activeEditor.getContent());
                });
            }
        });
        //切换tab
        $scope.toggleTab = function($event,index){
            if(!$scope.activity_id){
                notify('填写并保存内容设置',3);
            }else{
                $scope.tabIndex = index;
            }
        }
        $scope.goTemplate = function($event,isPreview){
            $state.go('template',{'activity_id': $scope.activity_id,'isEdit': $scope.isEdit,'isPreview':isPreview});
        }
        $scope.default = function(){}
        //提交活动
        $scope.submit = function($event,callback){
            console.log($scope.postData);
            var $btn = angular.element($event.target);
            if(!$btn.hasClass('disabled')){
                var validate = validateData();
                if(!validate.flag){
                    notify(validate.msg,3);
                }else{
                    $scope.postData.validations = [];
                    angular.forEach($scope.controls,function(item,i){
                        if(item.checked){
                            $scope.postData.validations.push({
                                type: item.value,
                                password: item.password
                            });
                        }
                    });
                    $btn.addClass('disabled');
                    $http({
                        method: $scope.activity_id?'PATCH':'POST',
                        url: $scope.activity_id?'/web-api/activities/'+$scope.activity_id+'/quizzes':'/web-api/activity/quizzes',
                        headers:  JSON.parse($('meta[name="profile"]').attr('content')),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        data: $scope.postData,
                    }).then(function(httpData){
                        var data = httpData.data;
                        $btn.removeClass('disabled');
                        if(data.code==200){
                            notify('保存成功',2);
                            if($scope.tabIndex==1) {
                                $scope.tabIndex = 2;
                            }
                            if(!$scope.activity_id){
                                $scope.activity_id = data.data.id;
                            }
                            if(callback){
                                setTimeout(callback,2000);
                            }
                        }else{
                            notify(data.message,3);
                        }
                    },function(httpData){
                        var data = httpData.data;
                        $btn.removeClass('disabled');
                        notify(data.message,3);
                    });
                }
            }
        };
        //返回
        $scope.goBack = function($event){
            window.history.go(-1);
        }
        //完成
        $scope.complete = function($event){
            $scope.submit(angular.element($event.target),function(){
                createChannel(function(){
                    location.href = '/web/activity/index';
                });
            });
        }
    }])
    .controller('templateController', ['$scope', '$timeout','$http', 'tinymceConfig', 'ngModal', 'notify','$stateParams','$state',function ($scope, $timeout,$http, tinymceConfig, ngModal, notify, $stateParams, $state) {
        $scope.question = '';
        $scope.questionArray = [];
        $scope.isEdit = $stateParams.isEdit=='true'?true:false;
        $scope.isPreview = $stateParams.isPreview=='true'?true:false;
        $scope.activity_id = $stateParams.activity_id;
        $scope.editIndex = -1;
        //获取问题类型
        $http.get('/web-api/quizzes/types',{}).success(function(data,status,headers,config){
            if(data.code==200){
                $scope.questionTypes = data.data;
            }else{
                notify(data.message,4);
            }
        }).error(function(data,status,headers,config){
            console.log('获取问题类型失败！');
        });
        //获取问题列表
        $http({
            method: 'GET',
            url: '/web-api/quizzes',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            params: {
                activity_id: $scope.activity_id,
                type: '',
                keyword: '',
                per_page: '200',
                page: '1'
            },
        }).success(function(data){
            if(data.code==200){
                angular.forEach(data.data.data,function(item,i){
                    $scope.questionArray.push({
                        id: item.id,
                        activity_id: item.activity_id,
                        type: item.type,
                        title: item.title,
                        required: item.validations.required||false,
                        linked: item.configurations.linked||false,
                        links:{
                            id: item.configurations.link_id,
                            option_ids: item.configurations.link_option_ids||[]
                        },
                        options: item.options
                    });
                });
            }else{
                notify(data.message,4);
            }
        }).error(function(data){
            console.log(data);
        });
        //编辑题目
        $scope.editQuestion = function(event,question,index){
            $scope.editIndex = index;
            $scope.question = JSON.parse(JSON.stringify(question));
        }
        //创建新题目
        $scope.createNew = function($event,type){
            $scope.editIndex = $scope.questionArray.length;
            $scope.question = {
                activity_id: $scope.activity_id,
                type: type,
                title: '',
                required: 0,
                linked: 0,
                links:{
                    id: '',
                    option_ids: []
                },
                options: []
            };
        }
        //选择图片上传弹框
        $scope.openImageModal = function($event,item){
            ngModal({
                templateUrl: '/components/imageModalContent.html',
                controller: 'imageModalController',
                resolve: {
                    items: function(){
                        return {
                          imgUrl: item.img
                        };
                    }
                },
                ok: function(data){
                    item.resource = data;
                },
                cancel: function(){

                }
            });
        }
        //关联逻辑弹出框
        $scope.openRelateModal = function($event,question){
            ngModal({
                templateUrl: '/components/quiz/relateModalContent.html',
                controller: 'relateModalController',
                resolve: {
                    items: function () {
                        return {
                            question: question,
                            questionArray: $scope.questionArray
                        };
                    }
                },
                ok: function (data) {
                    $scope.question = data;
                },
                cancel: function () {
                    $scope.question.linked = !$scope.question.linked;
                }
            });
        }
        $scope.postData = {}
        $scope.addOption = function ($event,index) {
            var obj = {
                text: '',
                resource: '',
                fillable: false,
                fill_required: 0,
                sort: 0
            };
            if (index == -1) {
                $scope.question.options.push(obj);
            } else {
                $scope.question.options.splice(index + 1, 0,obj);
            }
        }
        $scope.deleteOption = function ($event,item,index) {
            if(item.id){
                $http({
                    method: 'DELETE',
                    url: '/web-api/options/'+item.id,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                }).success(function(data){
                    if(data.code==200){
                        $scope.question.options.splice(index, 1);
                    }else{
                        notify(data.message,4);
                    }
                }).error(function(data){
                    notify('网络异常，稍后重试！',3);
                });
            }else{
                $scope.question.options.splice(index, 1);
            }
        }
        function sortOptionAjax(id,index){
            $http({
                method: 'PATCH',
                url: '/web-api/quizzes/'+id+'/sort',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: {
                    sort: index
                },
            }).success(function(data){
                if(data.code==200){

                }else{
                    notify(data.message,4);
                }
            }).error(function(data){
                notify('网络异常，稍后重试！',3);
            });
        }
        $scope.moveUpOption = function($event,item,index){
            var temp;
            temp = $scope.question[index];
            $scope.question[index] = $scope.question[index-1];
            $scope.question[index-1] = temp;
        }
        //验证是否存在重复选项
        function validateRepeatOption(options){
            var hash = {};
            for(var i in options) {
                if(hash[options[i].text]){
                    return true;
                }
                hash[options[i].text] = true;
            }
            return false;
        }
        //编辑问题单个选项
        function editOptions(options,quiz_id,$btn){
            if(validateRepeatOption(options)){
                notify('问题中选项重复',3);
                $btn.removeClass('disabled').text('完成编辑');
            }else {
                angular.forEach(options, function (item, i) {
                    $http({
                        method: item.id ? 'PATCH' : 'POST',
                        url: item.id ? '/web-api/options/' + item.id : '/web-api/quizzes/' + quiz_id + '/options',
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        data: item,
                    }).success(function (data) {
                        if (data.code == 200) {
                            if (i + 1 == options.length) {
                                $btn.removeClass('disabled').text('完成编辑');
                                $scope.questionArray[$scope.editIndex] = JSON.parse(JSON.stringify($scope.question));
                                $scope.editIndex = -1;
                            }
                        } else {
                            $btn.removeClass('disabled').text('完成编辑');
                            notify('"' + item.text + '"选项操作失败', 4);
                        }
                    }).error(function (data) {
                        $btn.removeClass('disabled').text('完成编辑');
                        notify('网络异常，稍后重试！', 3);
                    });
                });
            }
        }
        //批量编辑问题选项
        function editMultipleOptions(options,quiz_id,$btn){
            if(validateRepeatOption(options)){
                notify('问题中选项重复',3);
                $btn.removeClass('disabled').text('完成编辑');
            }else{
                $http({
                    method: 'POST',
                    url: '/web-api/quizzes/'+ quiz_id+'/multiple-options',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data: options,
                }).success(function(data){
                    if(data.code==200){
                        $btn.removeClass('disabled').text('完成编辑');
                        angular.forEach($scope.question.options,function(item,i){
                            item.id  = data.data[item.text];
                        });
                        $scope.questionArray[$scope.editIndex] = JSON.parse(JSON.stringify($scope.question));
                        $scope.editIndex = -1;
                    }else{
                        $btn.removeClass('disabled').text('完成编辑');
                        notify('选项操作失败',4);
                    }
                }).error(function(data){
                    $btn.removeClass('disabled').text('完成编辑');
                    notify('网络异常，稍后重试！',3);
                });
            }
        }
        //提交问题
        $scope.submitEdit = function($event){
            var $this = angular.element($event.target);
            var vflag = true;
            angular.forEach($scope.question.options,function(item,i){
                delete item.checked;
                if(!item.text){
                    vflag = false;
                }
            });
            if($scope.question.title==''){
                notify('请输入问题标题',4);
            }else if($scope.questionTypes[$scope.question.type]!='填空'&&$scope.question.options.length==0){
                notify('请设置选项',4);
            }else if(!vflag){
                notify('选项文案不能为空',4);
            }else{
                if(!$this.hasClass('disabled')){
                    $this.addClass('disabled').text('数据提交中...');
                    if(!$scope.question.id){
                        $http({
                            method: 'POST',
                            url: '/web-api/quizzes',
                            dataType: 'json',
                            contentType: "application/json; charset=utf-8",
                            data: $scope.question,
                        }).success(function(data){
                            $this.removeClass('disabled').text('完成编辑');
                            if(data.code == 200){
                                $scope.question.id = data.data.id;
                                $http.get('/web-api/quizzes/'+$scope.question.id+'/options').success(function(data,status,headers,config){
                                    if(data.code==200){
                                        $scope.question.options = data.data;
                                        $scope.questionArray.push($scope.question);
                                        $scope.question = '';
                                        $scope.editIndex = -1;
                                    }
                                });
                            }else{
                                notify(data.message,4);
                            }
                        }).error(function(data){
                            notify('网络异常，稍后重试！',3);
                        });
                    }else{
                        $http({
                            method: 'PATCH',
                            url: '/web-api/quizzes/'+$scope.question.id,
                            dataType: 'json',
                            contentType: "application/json; charset=utf-8",
                            data: $scope.question,
                        }).success(function(data){
                            if(data.code==200){
                                if($scope.questionTypes[$scope.question.type]!='填空'){
                                    editMultipleOptions($scope.question.options,$scope.question.id,$this);//批量
                                    // editOptions($scope.question.options,$scope.question.id,$this);//单个
                                }else{
                                    $this.removeClass('disabled').text('完成编辑');
                                    $scope.question = '';
                                    $scope.editIndex = -1;
                                }
                            }else{
                                $this.removeClass('disabled').text('完成编辑');
                                notify(data.message,4);
                            }
                        }).error(function(data){
                            notify('网络异常，稍后重试！',3);
                        });
                    }
                }
            }
        };
        $scope.cancelEdit = function($event){
            $scope.editIndex = -2;
        }
        //删除问题
        $scope.deleteQuestion = function($event,question,index){
            if(question.id){
                $http({
                    method: 'DELETE',
                    url: '/web-api/quizzes/'+question.id,
                }).success(function(data){
                    if(data.code==200){
                        $scope.questionArray.splice(index, 1);
                        notify('删除成功',2);
                    }else{
                        notify(data.code,4);
                    }
                }).error(function(data){
                    console.error(data);
                    notify('网络异常，稍后重试！',4);
                });
            }else{
                $scope.questionArray.splice(index, 1);
            }
        }
        //返回
        $scope.goBack = function($event){
           $state.go('form',{'tabIndex':2,'activity_id':$scope.activity_id});
        }
    }])
    .controller('exportController',['$scope','$timeout','$http','$state','notify','eChart','notify',function($scope,$timeout,$http,$state,$notify,eChart,notify){
        $scope.tabIndex = 1;
        $scope.tableSelected = true;
        $scope.setAllType = false;
        $scope.conditions = {
            quiz_id:[],
            option_ids: []
        };
        $scope.tags = [];
        $scope.resultData = {};
        $scope.allData = {};
        $scope.tagSelectedIndex = -1;
        function GetRequest() {
            var url = location.search; //获取url中"?"符后的字串
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=decodeURIComponent(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
        $scope.params = GetRequest();
        $scope.downloadHref = '/web-api/activities/'+$scope.params.activity_id+'/quizzes/download-pdf-report';
        $http({
            method: 'GET',
            url: '/web-api/activities/'+$scope.params.activity_id+'/quizzes/full-report',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
        }).success(function(data){
            if(data.code==200){
                $scope.allData = data.data;
                $scope.filterAllData = [];
                if(data.data&&data.data.length>0){
                    $scope.conditions.quiz_id.push(data.data[0].id);
                    angular.forEach($scope.allData,function(item,i){
                        if(item.type!=3){
                            $scope.filterAllData.push(item);
                        }
                    });
                }else{
                    $scope.conditions.quiz_id.push(null);
                }
            }else{
                notify(data.message,4);
            }
        }).error(function(data){
            console.log(data);
        });
        function getDataAjax(params){
            $http({
                method: 'POST',
                url: '/web-api/activities/'+$scope.params.activity_id+'/quizzes/category-report',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: params
            }).success(function(data){
                if(data.code==200){
                    $scope.resultData = data.data;
                }else{
                    notify(data.message,4);
                }
            }).error(function(data){
                console.log(data);
            });
        }
        $scope.$watch('conditions.quiz_id',function(){
            if($scope.conditions.quiz_id[0]!=$scope.conditions.quiz_id[1]){
                var option0=[],option1=[];
                $scope.tags = [];
                angular.forEach($scope.allData,function(item,i){
                    if(item.id==$scope.conditions.quiz_id[0]){
                        option0 = item.options;
                    }
                    if($scope.conditions.quiz_id.length==2 && item.id==$scope.conditions.quiz_id[1]){
                        option1 = item.options;
                    }
                });
                if(option0.length>0&&option1.length>0){
                    for(var i=0;i<option0.length;i++){
                        for(var j=0;j<option1.length;j++){
                            $scope.tags.push({
                                text:option0[i].text+' —— '+option1[j].text,
                                option_ids: [option0[i].id,option1[j].id]
                            });
                        }
                    }
                }else if(option0.length>0){
                    for(var i=0;i<option0.length;i++){
                        $scope.tags.push({
                            text:option0[i].text,
                            option_ids: [option0[i].id]
                        });
                    }
                }
            }else if($scope.conditions.quiz_id[0] && $scope.conditions.quiz_id[1]){
                notify('不能选择相同问题',4);
                $timeout(function(){
                    $scope.conditions.quiz_id[1] = null;
                },1);
            }
            $scope.tagSelectedIndex = -1;
            $scope.resultData.quizzes = [];
        },true);
        $scope.requestData = function(tag,index){
            $scope.tagSelectedIndex = index;
            $scope.conditions.option_ids = tag.option_ids;
            getDataAjax($scope.conditions);
        }
        $scope.togglePanel = function(index){
            $scope.tabIndex = index;
        }
        $scope.toggleTypeTab1 = function(bool){
            $scope.setAllType1 = bool;
            angular.forEach($scope.allData,function(item,i){
                item.setSingleType = bool;
            });
        }
        $scope.toggleTypeTab2 = function (bool) {
            $scope.setAllType2 = bool;
            angular.forEach($scope.resultData.quizzes, function (item, i) {
                item.setSingleType = bool;
            });
        }
        $scope.goBack = function($event){
            window.history.go(-1);
        }
        $scope.goSheetPage = function($event){
            $state.go('sheet',{});
        }
        $scope.addCondition = function(){
            $scope.conditions.quiz_id.length = 2;
        }
        $scope.deleteCondition = function(){
            $scope.conditions.quiz_id.length = 1;
        }
        //下载导出数据
        $scope.export = function($event){
            $http({
                method: 'GET',
                url: $scope.downloadHref,
            }).success(function(data){
                if(data.code==200){
                    $scope.resultData = data.data;
                }else{
                    notify(data.message,4);
                }
            }).error(function(data){
                console.log(data);
            });
        }
    }])
    .controller('sheetController',['$scope','$timeout','$http','notify','eChart',function($scope,$timeout,$http,notify,eChart){
        $scope.numbers = [1];
        function GetRequest() {
            var url = location.search; //获取url中"?"符后的字串
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=decodeURIComponent(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
        $scope.params = GetRequest();
        $scope.goBack = function($event){
            window.history.go(-1);
        }
        $scope.papers = {};//问卷列表
        $scope.onePaper = null;//单个问卷
        $scope.pagination = {
            pageSize: 8,
            pageIndex: 1,
            lastPage: 1
        }
        function paperAjax(){
            $http({
                method: 'GET',
                url: '/web-api/activities/'+$scope.params.activity_id+'/papers',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                params: {
                    per_page:$scope.pagination.pageSize,
                    page: $scope.pagination.pageIndex
                },
            }).success(function(data){
                if(data.code==200){
                    $scope.papers = data.data;
                    $scope.pagination.lastPage = data.data.last_page;
                    if(data.data.last_page>0){
                        $scope.numbers = [];
                        for(var i=1;i<=data.data.last_page;i++){
                            $scope.numbers.push(i);
                        }
                    }
                }else{
                    notify(data.message,4);
                }
            }).error(function(data){
                console.log(data);
            });
        }
        paperAjax();
        $scope.checkInfo = function($event,paper,index){
            $scope.onePaper = $scope.papers.data[index];
            $http({
                method: 'GET',
                url: '/web-api/papers/'+paper.id,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
            }).success(function(data) {
                if (data.code == 200) {
                    $scope.onePaperAnswer = data.data;
                } else {
                    notify(data.message, 4);
                }
            });
        }
        $scope.deleteInfo = function($event,paper,index){
            $http({
                method: 'DELETE',
                url: '/web-api/papers/'+paper.id,
            }).success(function(data) {
                if (data.code == 200) {
                    notify('删除成功', 4);
                    $scope.papers.data.splice(index, 1);
                } else {
                    notify(data.message, 4);
                }
            });
        }
        $scope.jumpPage = function(index){
            $scope.pagination.pageIndex = index;
            paperAjax();
        }
    }])
    .controller('imageModalController',['$scope','$timeout','$modalInstance','notify','items',function ($scope,$timeout,$modalInstance,notify,items) {
        var $mBody = '';
        $scope.config = {
            id: '001',
            fileSize: 2*1024*1024
        }
        $scope.base64 = '';
        $scope.filePath = '';
        $scope.httpPath = '';
        $scope.src = '';
        if(items.imgUrl){
            $scope.src = items.imgUrl;
            $scope.httpPath = items.imgUrl;
        }
        $scope.confirm = function($event){
            $timeout(function(){
                $scope.src = $scope.httpPath;
            },10);
        }
        $scope.delete = function($event){
            $mBody = angular.element($event.target).parents('.m-body');
            var fileDom = angular.element($event.target).parents('.m-body').find('input[type=file]');
            fileDom.outerHTML = fileDom.outerHTML;
            $scope.src = '';
            $scope.httpPath = '';
            $scope.base64 = '';
        }
        $scope.ok = function ($event) {
            var $form = angular.element($event.target).parents('#imageModalContent').find('form[name=imgUpload]');
            var $file = $form.find('input[type=file]');
            if($file[0].files.length>0){
                $.ajax({
                    type: "POST",
                    url: "tmp/upload",
                    processData: false,
                    contentType: false,
                    data: new FormData($form[0]),
                    cache: false,
                    async: false,
                    success: function (data) {
                        if(data.code == 0){
                            $modalInstance.close(data.result.url);
                        }else{
                            notify(data.message,4);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("上传失败，请检查网络后重试");
                    }
                });
            }else{
                if($scope.src){
                    $modalInstance.close($scope.src);
                }else{
                    notify('请选择一张图片',4);
                }
            }
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    }])
    .controller('relateModalController',['$scope','$timeout','$http','$modalInstance','notify','items',function ($scope,$timeout,$http,$modalInstance,notify,items) {
        $scope.question = items.question;
        $scope.questionArray = items.questionArray;
        $scope.linkQuestions = {};//可关联问题
        $scope.linkQuestionsOptions = {};//可关联问题全部选项
        $scope.linkoptions = [];//选中关联问题关联选项
        $http({
            method: 'GET',
            url: '/web-api/quizzes/'+$scope.question.activity_id+'/unlinked?without='+$scope.question.id,
            dataType: 'json',
            contentType: "application/json",
        }).success(function(data){
            if(data.code==200){
                $scope.linkQuestions = data.data;
                angular.forEach($scope.questionArray,function(item,i){
                    for(var j=0;j<$scope.linkQuestions.length;j++){
                        if($scope.linkQuestions[j].id == item.id){
                            $scope.linkQuestionsOptions[item.id] = item.options;
                        }
                    }
                });
                $scope.$watch('question.links.id',function(){
                    if($scope.question.links.id){
                        $scope.linkoptions = $scope.linkQuestionsOptions[$scope.question.links.id];
                        angular.forEach($scope.linkoptions,function(item,i){
                            angular.forEach($scope.question.links.option_ids,function(id,j){
                                if(id==item.id){
                                    item.checked = true;
                                }
                            });
                        });
                    }else{
                        $scope.linkoptions = [];
                    }
                },true);
            }else{
                notify(data.message,4);
            }
        }).error(function(data){
            notify('网络异常，稍后重试!',4);
            console.log(data);
        });
        $scope.ok = function ($event) {
            if($scope.question.links.id==''){
                notify('请选择关联问题',2);
                return;
            }
            $scope.question.links.option_ids = [];
            angular.forEach($scope.linkoptions, function (item, i) {
                if (item.checked) {
                    $scope.question.links.option_ids.push(item.id);
                }
            });
            if($scope.question.links.option_ids.length==0){
                notify('请选择关联选项',4);
                return;
            }
            $scope.question.linked = true;
            $modalInstance.close($scope.question);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
        $scope.delete = function(){
            $scope.question.linked = false;
            $scope.question.links.id = '';
            $scope.question.links.option_ids = [];
            $modalInstance.close($scope.question);
        }
    }]);